<?php

namespace App\Models\Admin;

use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Model;

class Admins extends Model
{
    protected $table = 'admins';

    public $guarded = [];

    public $timestamps = true;

    /**
     * 添加
     * @data int $ 数据
     */
    public static function add($data)
    {
        Log::info('添加管理员:', $data);
        $save_data = [
            'account' => $data['account'],
            'password' => sha1($data['password']),
            'phone' => $data['phone'],
            'remark' => $data['remark'],
            'role' => "代理管理员",
            'status' => 1,
        ];
        try {
            $check = self::where('account', $data['account'])->first();
            if ($check) return result_json(409, '账号已存在');
            $save = self::create($save_data);
            if (!$save) {
                return result_json(500, '失败');
            }
            return result_json(200, '成功');
        } catch (Exception $e) {
            Log::error("添加管理员 Caught exception::", $e->getMessage(), '<br>');
            return result_json(500, '失败');
        }
    }

    /**
     * 编辑
     * @data int $ 数据
     */
    public static function edit($data)
    {
        Log::info('编辑管理员:', $data);
        $save_data = [
            'account' => $data['account'],
            'phone' => $data['phone'],
            'remark' => $data['remark'],
            'role' => "代理管理员",
        ];
        try {
            $save = self::where(['id' => $data['id']])->update($save_data);
            if (!$save) result_json(500, '失败');
            return result_json(200, '成功');
        } catch (Exception $e) {
            Log::error("编辑管理员 Caught exception::", $e->getMessage(), '<br>');
            return result_json(500, '失败');
        }
    }

    /**
     * 获取列表
     * @param $data
     * @return array|string
     */
    public static function getList($data)
    {
        $sort = !isset($data['sort']) ? [] : (is_array(json_decode($data['sort'], true)) ? json_decode($data['sort'], true) : []);
        $list = self::where(['role' => '代理管理员'])
            ->when(isset($data['keywords']) && !empty($data['keywords']), function ($query) use ($data) {
                $query->where('account', 'like', '%' . $data['keywords'] . '%');
                $query->orWhere('phone', 'like', '%' . $data['keywords'] . '%');
                $query->orWhere('remark', 'like', '%' . $data['keywords'] . '%');
                return $query;
            })
            ->when($sort, function ($query) use ($sort) {
                foreach ($sort as $k => $vo) {
                    $query->orderBy($k, $vo);
                }
                return $query;
            })
            ->orderBy('id', 'desc')
            ->paginate($data['limit']);
        return $list;
    }

    /**
     * 更改状态
     * @param $data
     * @return array|string
     */
    public static function changeStatus($data)
    {
        Log::info('更改管理员状态:', $data);
        $save_data = [
            'status' => $data['status'],
        ];
        try {
            $save = self::where(['id' => $data['id']])->update($save_data);
            return result_json(200, '成功');
        } catch (Exception $e) {
            Log::error("更改管理员状态失败 Caught exception::", $e->getMessage(), '<br>');
            return result_json(500, '失败');
        }
    }

    /**
     * 获取信息
     * @param $data
     * @return array|string
     */
    public static function getInfo($data)
    {
        $info = self::where(['id' => $data['id']])->first();
        if (!$info) return ['id' => 0, 'account' => "", 'phone' => '', 'remark' => ""];
        $info = $info->toArray();
        return $info;
    }

    /**
     * 删除
     * @data int $ 数据
     */
    public static function del($data)
    {
        Log::info('删除管理员:', $data);
        try {
            $list = self::where('id', $data['id'])->delete();
            return result_json(200, '成功');
        } catch (Exception $e) {
            Log::error("删除管理员 Caught exception::", $e->getMessage(), '<br>');
            return result_json(500, '失败');
        }
    }


    /**
     * 检查登陆
     * @param $data
     * @return array|string
     */
    public static function checkLogin($data)
    {
        $admins = self::where(['account' => $data['account'], 'status' => 1])->first();
        if (!$admins) return result_json(409, '账号或密码错误');
        if ($admins['password'] != sha1($data['password'])) return result_json(409, '账号或密码错误');
        session()->put('id', $admins['id']);
        session()->put('account', $admins['account']);
        return result_json(200, '成功', ['route' => '/myadmin/index']);
    }

    /**
     * 修改密码
     * @param $data
     * @return array|string
     */
    public static function changePassword($data)
    {
        $admins = self::where('id', $data['user']['uid'])->first();
        if (!$admins) return result_json(409, '账号不存在');
        if ($admins['password'] != sha1($data['old_pwd'])) return result_json(409, '旧密码错误');
        try {
            $save = self::where('id', $data['user']['uid'])->update(['password' => sha1($data['new_pwd'])]);
            if (!$save) return result_json(500, '失败');
            self::loginOut();
            return result_json(200, '成功');
        } catch (Exception $e) {
            Log::error("管理员修改密码失败 Caught exception::", $e->getMessage(), '<br>');
            return result_json(500, '失败');
        }
        return result_json(200, '成功', ['route' => '/myadmin/index']);
    }

    /**
     * 退出登录
     */
    public static function loginOut()
    {
        session()->forget('id');
        session()->forget('account');
    }

}